from rqalpha.apis import *
import time
from rqalpha.environment import Environment
from rqalpha.my_factors.reform_data import get_cash_flow_in_factors
from rqalpha import run_func

config = {
    "base": {
        "start_date": "2021-07-31",
        "end_date": "2021-07-31",
        "frequency": "tick",
        "accounts": {
            "stock": 10000000
        }
    },

    "extra": {
        "log_level": "info",
    },

    "mod": {
        "my_backtest": {
            "enabled": True
        },
        "sys_analyser": {
            "enabled": True,
            "benchmark": "000300.XSHG",
            "plot": True,
            # "plot": False,
            "report_save_path": "C:\\Users\\huajia\Desktop\\rqalpha4\\rqalpha\\plot_result"
        },
        "sys_simulation": {
            "enabled": True,
            "matching_type": "last",
        },
        "sys_accounts": {
            "enabled": True,
            "validate_stock_position": False,
            "stock_t1": False
        },
        "incremental": {
            "enabled": True,
            "strategy_id": "1",
            # 是否启用 csv 保存 feeds 功能，可以设置为 MongodbRecorder
            "recorder": "CsvRecorder",
            # 持久化数据输出文件夹
            "persist_folder": "C:\\Users\huajia\\Desktop\\rqalpha4\\rqalpha\\incremental_result",
            # "persist_folder": None,
            # mongodb
            "mongo_url": "mongodb://localhost",
            "mongo_dbname": "rqalpha_records",
        }
    }
}


def run_bt(config, my_defines):
    # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
    def init(context):
        logger.info("init------------")
        _env = Environment.get_instance()
        symbol = _env.config.base.all_symbols_mapping
        dt = my_defines['config.base']['start_date']
        # print(symbol)
        data = _env.data_source.ticks_data
        logger.info("get factors---")
        q1, q2, q3, q4, q5 = get_cash_flow_in_factors(data)
        context.s1 = symbol
        context.q1 = q1
        context.q2 = q2
        context.q3 = q3
        context.q4 = q4
        context.q5 = q5
        my_defines['all_queue'].append([dt, *q1])
        my_defines['all_queue'].append([dt, *q2])
        my_defines['all_queue'].append([dt, *q3])
        my_defines['all_queue'].append([dt, *q4])
        my_defines['all_queue'].append([dt, *q5])
        update_universe(context.s1)
        subscribe(context.s1)

    def before_trading(context):
        print('before trading ++++++++')
        print(context.q1)
        print(context.q2)
        print(context.q3)
        print(context.q4)
        print(context.q5)
        # print(my_defines['queue1'])
        # print(my_defines['all_queue'])
        # time.sleep(500)

    def handle_tick(context, tick):
        # print(tick.order_book_id)
        # print(tick)
        if tick.order_book_id in context.q1 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            # print('=================', my_defines['queue1'])
            if tick.order_book_id in my_defines['queue1'] and tick.datetime.date() > \
                    my_defines['queue1'][tick.order_book_id].date():
                order_shares(tick.order_book_id, -100)
                del my_defines['queue1'][tick.order_book_id]
                order_shares(tick.order_book_id, 100)
                my_defines['queue1'][tick.order_book_id] = tick.datetime
            if tick.order_book_id not in my_defines['queue1']:
                order_shares(tick.order_book_id, 100)
                my_defines['queue1'][tick.order_book_id] = tick.datetime
            # print('=================', my_defines['queue1'])
            # time.sleep(500)
        if tick.order_book_id not in context.q1 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            # print('---------------------------------')
            if tick.order_book_id not in my_defines['queue1']:
                pass
            if tick.order_book_id in my_defines['queue1']:
                order_shares(tick.order_book_id, -100)
                del my_defines['queue1'][tick.order_book_id]

        if tick.order_book_id in context.q2 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id in my_defines['queue2'] and tick.datetime.date() > \
                    my_defines['queue2'][tick.order_book_id].date():
                order_shares(tick.order_book_id, -100)
                del my_defines['queue2'][tick.order_book_id]
                order_shares(tick.order_book_id, 100)
                my_defines['queue2'][tick.order_book_id] = tick.datetime
            if tick.order_book_id not in my_defines['queue2']:
                order_shares(tick.order_book_id, 100)
                my_defines['queue2'][tick.order_book_id] = tick.datetime
        if tick.order_book_id not in context.q2 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id not in my_defines['queue2']:
                pass
            if tick.order_book_id in my_defines['queue2']:
                order_shares(tick.order_book_id, -100)
                del my_defines['queue2'][tick.order_book_id]

        if tick.order_book_id in context.q3 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id in my_defines['queue3'] and tick.datetime.date() > \
                    my_defines['queue3'][tick.order_book_id].date():
                order_shares(tick.order_book_id, -100)
                del my_defines['queue3'][tick.order_book_id]
                order_shares(tick.order_book_id, 100)
                my_defines['queue3'][tick.order_book_id] = tick.datetime
            if tick.order_book_id not in my_defines['queue3']:
                order_shares(tick.order_book_id, 100)
                my_defines['queue3'][tick.order_book_id] = tick.datetime
        if tick.order_book_id not in context.q3 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id not in my_defines['queue3']:
                pass
            if tick.order_book_id in my_defines['queue3']:
                order_shares(tick.order_book_id, -100)
                del my_defines['queue3'][tick.order_book_id]

        if tick.order_book_id in context.q4 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id in my_defines['queue4'] and tick.datetime.date() > \
                    my_defines['queue4'][tick.order_book_id].date():
                order_shares(tick.order_book_id, -100)
                del my_defines['queue4'][tick.order_book_id]
                order_shares(tick.order_book_id, 100)
                my_defines['queue4'][tick.order_book_id] = tick.datetime
            if tick.order_book_id not in my_defines['queue4']:
                order_shares(tick.order_book_id, 100)
                my_defines['queue4'][tick.order_book_id] = tick.datetime
        if tick.order_book_id not in context.q4 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id not in my_defines['queue4']:
                pass
            if tick.order_book_id in my_defines['queue4']:
                order_shares(tick.order_book_id, -100)
                del my_defines['queue4'][tick.order_book_id]

        if tick.order_book_id in context.q5 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id in my_defines['queue5'] and tick.datetime.date() > \
                    my_defines['queue5'][tick.order_book_id].date():
                order_shares(tick.order_book_id, -100)
                del my_defines['queue5'][tick.order_book_id]
                order_shares(tick.order_book_id, 100)
                my_defines['queue5'][tick.order_book_id] = tick.datetime
            if tick.order_book_id not in my_defines['queue5']:
                order_shares(tick.order_book_id, 100)
                my_defines['queue5'][tick.order_book_id] = tick.datetime
        if tick.order_book_id not in context.q5 and tick.datetime.strftime('%H:%M:%S') == '14:59:00':
            if tick.order_book_id not in my_defines['queue5']:
                pass
            if tick.order_book_id in my_defines['queue5']:
                order_shares(tick.order_book_id, -100)
                del my_defines['queue5'][tick.order_book_id]

    def after_trading(context):
        print('after trading----------------')
        # logger.info(data.tail(3))
        context.all_df = pd.DataFrame(data=my_defines['all_queue'])
        context.all_df.to_csv('./context_df.csv')
        # time.sleep(500)

    run_func(config=config, init=init, before_trading=before_trading, handle_tick=handle_tick,
             after_trading=after_trading, my_defines=my_defines)


